//
//  HttpRequest.m
//  基于AFNetWorking的再封装
//
//  Created by 吴红星 on 16/1/2.
//  Copyright © 2016年 wuhongxing. All rights reserved.
//

#import "HttpRequest.h"
#import "AFNetworking.h"
#import "AFNManager.h"


@implementation HttpRequest

static HttpRequest *singleton = nil;
+ (instancetype)sharedInstance {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        singleton = [[self alloc] init];
    });
    return singleton;
}

#pragma mark -- GET请求 --
- (void)getWithURLString:(NSString *)URLString
              parameters:(id)parameters
                 success:(void (^)(id))success
                 failure:(void (^)(NSError *))failure {
    
    AFHTTPSessionManager *manager = [AFNManager shareManager];;
    /**
     *  可以接受的类型
     */
    AFHTTPRequestSerializer *requestSerializer = [AFHTTPRequestSerializer serializer];
    [self addBaseParamForRequest:requestSerializer];
    
    manager.requestSerializer = requestSerializer;

    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    
    
    /**
     *  请求队列的最大并发数
     */
    manager.operationQueue.maxConcurrentOperationCount = 5;
    /**
     *  请求超时的时间
     */
    manager.requestSerializer.timeoutInterval = 30;
    [manager GET:URLString parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if ([responseObject isKindOfClass:[NSData class]]) {
            id json = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            if (json) {
                if (success) {
                    success(json);
                }
            } else {
                DLog(@"返回结果 不是有效的json 格式, 不处理");
            }
        } else {
            if (success) {
                success(responseObject);
            }
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(error);
        }
    }];
}

#pragma mark -- POST请求 --
- (void)postWithURLString:(NSString *)URLString
               parameters:(id)parameters
                  success:(void (^)(id))success
                  failure:(void (^)(NSError *))failure {

    /*  获取请求管理者  */
    AFHTTPSessionManager *manager = [AFNManager shareManager];
    
    AFHTTPRequestSerializer *requestSerialize = [AFJSONRequestSerializer serializer];
    [self addBaseParamForRequest:requestSerialize];
    
    manager.requestSerializer = requestSerialize ;
    
//    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    

    manager.requestSerializer.timeoutInterval=30.f;
    
    manager.responseSerializer.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"application/xml", @"text/xml",@"text/json",@"text/html",@"application/json",@"text/plain",@"image/jpg",nil];
    
    
    [manager POST:URLString parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if ([responseObject isKindOfClass:[NSData class]]) {
            id json = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            if (json) {
                if (success) {
                    success(json);
                }
            } else {
                DLog(@"返回结果 不是有效的json 格式, 不处理");
            }
        } else {
            if (success) {
                success(responseObject);
            }
        }

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(error);
        }
    }];
}


 


- (void)canceCurrentRequest {
    DLog(@"cancel all request");
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    for (NSURLSessionTask *task in manager.tasks) {
        [task cancel];
    }
}


- (void)postTFFormWithURLString:(NSString *)URLString
                 parameters:(id)parameters
                    success:(void (^)(id responseObject))success
                    failure:(void (^)(NSError *error))failure {
    
    AFHTTPSessionManager *manager = [AFNManager shareManager];
    
    AFHTTPRequestSerializer *requestSerializ = [AFHTTPRequestSerializer serializer];
    [self addBaseParamForRequest:requestSerializ];
    manager.requestSerializer = requestSerializ;
    
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    
    [manager POST:URLString parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        
        if ([responseObject isKindOfClass:[NSData class]]) {
            id json = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            if (json) {
                if (success) {
                    success(json);
                }
            } else {
                DLog(@"返回结果 不是有效的json 格式, 不处理");
            }
        } else {
            if (success) {
                success(responseObject);
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(error);
        }
    }];
}


- (void)uploadDataWithImage:(UIImage *)image
                  URLString:(NSString *)URLString
                     parameters:(id)parameters
                        success:(void (^)(id responseObject))success
                        failure:(void (^)(NSError *error))failure {

    NSString *fileName = @"head.jpg";
    NSString *mimeType = @"image/jpeg";
    
    NSData *data = UIImageJPEGRepresentation(image, 0.8);
    
    if (!data) {
        fileName = @"head.png";
        mimeType = @"image/png";
        data = UIImagePNGRepresentation(image);
    }
    
    AFHTTPSessionManager *manager = [AFNManager shareManager];
    AFHTTPRequestSerializer *requestSerializ = [AFHTTPRequestSerializer serializer];
    [self addBaseParamForRequest:requestSerializ];
    manager.requestSerializer = requestSerializ;
    
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    
    [manager POST:URLString parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [formData appendPartWithFileData:data name:@"file" fileName:fileName mimeType:mimeType];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([responseObject isKindOfClass:[NSData class]]) {
            id json = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            if (json) {
                if (success) {
                    success(json);
                }
            } else {
                DLog(@"返回结果 不是有效的json 格式, 不处理");
            }
        } else {
            if (success) {
                success(responseObject);
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(error);
        }
    }];
 
    
}


- (void)uploadFeedDataWithImages:(NSMutableArray *)images
                  URLString:(NSString *)URLString
                 parameters:(id)parameters
                    success:(void (^)(id responseObject))success
                    failure:(void (^)(NSError *error))failure {
    
    NSString *fileNameOne = @"one.jpg";
    NSString *fileNameTwo = @"two.jpg";
    NSString *fileNameThree = @"three.jpg";

    NSString *mimeType = @"image/jpeg";
    
    NSData *dataOne = nil;
    NSData *dataTwo = nil;
    NSData *dataThree = nil;

    NSInteger number = images.count;
    
    if (number == 0) {//无图
        
    } else if (number == 1) {
        dataOne = UIImageJPEGRepresentation(images[0], 0.8);
        if (!dataOne) {
            fileNameOne = @"one.png";
            mimeType = @"image/png";
            dataOne = UIImagePNGRepresentation(images[0]);
        }
    } else if (number == 2) {
        dataOne = UIImageJPEGRepresentation(images[0], 0.8);
        if (!dataOne) {
            fileNameOne = @"one.png";
            mimeType = @"image/png";
            dataOne = UIImagePNGRepresentation(images[0]);
        }
        dataTwo = UIImageJPEGRepresentation(images[0], 0.8);
        if (!dataTwo) {
            fileNameTwo = @"two.png";
            mimeType = @"image/png";
            dataTwo = UIImagePNGRepresentation(images[0]);
        }
    } else if (number == 3) {
        dataOne = UIImageJPEGRepresentation(images[0], 0.8);
        if (!dataOne) {
            fileNameOne = @"one.png";
            mimeType = @"image/png";
            dataOne = UIImagePNGRepresentation(images[0]);
        }
        dataTwo = UIImageJPEGRepresentation(images[0], 0.8);
        if (!dataTwo) {
            fileNameTwo = @"two.png";
            mimeType = @"image/png";
            dataTwo = UIImagePNGRepresentation(images[0]);
        }
        dataThree = UIImageJPEGRepresentation(images[0], 0.8);
        if (!dataThree) {
            fileNameThree = @"three.png";
            mimeType = @"image/png";
            dataThree = UIImagePNGRepresentation(images[0]);
        }
    }
    
    AFHTTPSessionManager *manager = [AFNManager shareManager];
    AFHTTPRequestSerializer *requestSerializ = [AFHTTPRequestSerializer serializer];
    [self addBaseParamForRequest:requestSerializ];
    manager.requestSerializer = requestSerializ;
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    
//#define BaseHostUrl   @"http://devtest.Liyadongyc.com:3004"

//    URLString = @"http://192.168.31.30:9860/access/order/feedback";
    
    DLog(@"feedback url and param = %@, %@, image number = %ld", URLString,parameters,(long)number);
    
    
    [manager POST:URLString parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        if (dataOne) {
            [formData appendPartWithFileData:dataOne name:@"picture1" fileName:fileNameOne mimeType:mimeType];
        }
        if (dataTwo) {
            [formData appendPartWithFileData:dataTwo name:@"picture2" fileName:fileNameTwo mimeType:mimeType];
        }
        if (dataThree) {
            [formData appendPartWithFileData:dataThree name:@"picture3" fileName:fileNameThree mimeType:mimeType];
        }
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([responseObject isKindOfClass:[NSData class]]) {
            id json = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            if (json) {
                if (success) {
                    success(json);
                }
            } else {
                DLog(@"返回结果 不是有效的json 格式, 不处理");
            }
        } else {
            if (success) {
                success(responseObject);
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(error);
        }
    }];
    
    
}


- (void)addBaseParamForRequest:(AFHTTPRequestSerializer *)requestSerializer {
    
//    TFUserModel *user = [[TFUserInfoTool shareInstance] getCurrentUserInfo];
//    if (!user || !user.isLogin) {
//        return;
//    }
//
//    if (!user.token || ![user.memberId stringValue]) {
//        return;
//    }
//    NSDictionary *headerFieldValueDictionary = @{
//                                                 @"token":user.token,
//                                                 @"passengerId":[user.memberId stringValue],
//                                                 };
//    
//    if (headerFieldValueDictionary != nil) {
//        for (NSString *httpHeaderField in headerFieldValueDictionary.allKeys) {
//            NSString *value = headerFieldValueDictionary[httpHeaderField];
//            [requestSerializer setValue:value forHTTPHeaderField:httpHeaderField];
//        }
//    }
    
}

@end
